<?php
namespace app\api\controller\v1;
use app\api\logic\SendMuLogic;
use think\Db;
use app\service\TechnService;
use app\service\PaymentService;
use app\service\OrderService;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
class Order extends Base
{
	public function _initialize()
	{
		parent::_initialize();
//		$this->IsLogin(); //验证登录
	}

	/**
	 * 订单支付
	 */
	public function pay()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可支付']);
            exit();
        }
        //查询技师
        $techn = Db::name('techn')->where(['id' => $order_info['techn_id']])->find();
        if(empty($techn))
		{
			echo json_encode(['code' => -1, 'msg' => '技师不存在']);
            exit();
		}
		//判断技师是否在接单状态
		if($techn['work_status'] != 1)
		{
			echo json_encode(['code' => -1, 'msg' => '技师不在工作状态']);
            exit();
		}
		//判断预约时间是否大于当前时间
		$pre_start_time = $order_info['pre_start_time'];
		if((time()+900) >= $pre_start_time)
		{
			echo json_encode(['code' => -1, 'msg' => '超过预约时间']);
            exit();
		}
		
		
		
		//技师预约时间节点
        $reservation_node = [];
        //查询技师已预约的订单
        $order_list = Db::name('order')->where(['techn_id' => $techn['id'], 'id' => ['neq', $order_info['id']], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->select();
        if(!empty($order_list))
        {
        	foreach($order_list as $key => $value)
        	{
        		if(!empty($value['pre_start_time']) && !empty($value['pre_end_time']))
        		{
        			//处理时间节点
        			$new_pre_start_time = $value['pre_start_time'];
        			$new_pre_end_time = $value['pre_end_time']+900;
        			for($j = $new_pre_start_time; $j <= $new_pre_end_time; $j += 1800)
        			{
        				$reservation_node[] = date('Y-m-d H:i:s', $j);
        			}
        		}
        	}
        }
        $techn['no_pre_hour_slot'] = !empty($techn['no_pre_hour_slot']) ? json_decode($techn['no_pre_hour_slot'], true) : [];
        //判断是否在技师工作时间
        //判断是否选择接单开始时间与结束时间
        $work_start_hour = !empty($techn['work_start_hour']) ? strtotime(date('Y-m-d', $pre_start_time).' '.$techn['work_start_hour'].':00') : strtotime(date('Y-m-d', $pre_start_time).' 00:00:00');
        $work_end_hour = !empty($techn['work_end_hour']) ? strtotime(date('Y-m-d', $pre_start_time).' '.$techn['work_end_hour'].':00') : strtotime(date('Y-m-d', $pre_start_time).' 23:30:00');
        if($work_start_hour > $work_end_hour)
		{
			if(!(($pre_start_time >= $work_start_hour || $pre_start_time <= $work_end_hour) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
			{
				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
			}
		}elseif ($work_start_hour < $work_end_hour) {
			if(!($pre_start_time >= $work_start_hour && $pre_start_time <= $work_end_hour && !in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
			{
				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
			}
		}else
		{
			if(!(!in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
			{
				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
			}
		}


        // 支付方式
        $payment_array = PaymentService::$payment_array;
        $payment = $payment_array[$order_info['payment_id']];
        if(empty($payment))
        {
        	echo json_encode(['code' => -1, 'msg' => '支付方式有误']);
			exit();
        }
        //支付参数
        $pay_data = [
        	'user' => $params['user'],
        	'order_id' => $order_info['id'],
        	'order_no' => $order_info['order_no'],
        	'name' => '订单支付',
        	'total_price' => $order_info['total_price'],
        	'client_type' => $order_info['client_type'],
        	'notify_url' => request()->domain().'/api/v1/ordernotify/'.strtolower($payment['payment']),
        	'call_back_url' => request()->domain().'/h5/pages/order/order',
        	'redirect_url' => '',
        	'site_name' => '摩小妹',
        	'ajax_url' => '',
        ];
        // 发起支付
        $pay_name = 'payment\\'.$payment['payment'];
        $ret = (new $pay_name($payment['config']['user']))->Pay($pay_data);
        if(isset($ret['code']) && $ret['code'] == 0)
        {
        	$result = $ret;
        }else
        {
        	$result['code'] = -100;
        	$result['msg'] = empty($ret['msg']) ? '支付接口异常' : $ret['msg'];
        }
        echo json_encode($result);
	}
	
	
	
	
	
	/**
	 * 订单支付----加钟
	 */
	public function jzpay()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		
		
        //查询订单信息
        $order_info = Db::name('order_jz')->where(['id' => $params['order_id']])->find();
        
        $order=db::name('order')->where('id',$order_info['order_id'])->find();
        
		$pre_end_time=$order['pre_end_time'];
		
		
		if($order['status']==2||$order['status']==3||$order['status']==4||$order['status']==5){
		    
		}else if($order['status']==6&&time()-$pre_end_time<600){
		    
		}else{
		    echo json_encode(['code' => -1, 'msg' => '本次订单已不可加钟']);
			exit();
		}
		
        // 支付方式
        $payment_array = PaymentService::$payment_array;
        $payment = $payment_array[$order_info['payment_id']];
        if(empty($payment))
        {
        	echo json_encode(['code' => -1, 'msg' => '支付方式有误']);
			exit();
        }
        
        //支付参数
        $pay_data = [
        	'user' => $params['user'],
        	'order_id' => $order_info['id'],
        	'order_no' => $order_info['order_no'],
        	'name' => '订单支付',
        	'total_price' => $order_info['price'],
        	'client_type' => 'h5',
        	'notify_url' => request()->domain().'/api/v1/ordernotify/'.strtolower($payment['jzpayment']),
        	'call_back_url' => request()->domain().'/h5/pages/order/order',
        	'redirect_url' => '',
        	'site_name' => '摩小妹',
        	'ajax_url' => '',
        ];
        
        
        
        // 发起支付
        $pay_name = 'payment\\'.$payment['jzpayment'];
        if($order_info['payment_id']==1){
            $pay_name = 'payment\Weixin';
        }
        $ret = (new $pay_name($payment['config']['user']))->Pay($pay_data);
        if(isset($ret['code']) && $ret['code'] == 0)
        {
        	$result = $ret;
        }else
        {
        	$result['code'] = -100;
        	$result['msg'] = empty($ret['msg']) ? '支付接口异常' : $ret['msg'];
        }
        echo json_encode($result);
	}
	
	
	
	// 升级
	public function upgrade_pay()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		
		
        //查询订单信息
        $order_info = Db::name('order_upgrade')->where(['id' => $params['order_id']])->find();
        
        $order=db::name('order')->where('id',$order_info['order_id'])->find();
        
		$pre_end_time=$order['pre_end_time'];
		
		
		if($order['status']!=5){
		    echo json_encode(['code' => -1, 'msg' => '本次订单已不可操作']);
			exit();
		}
		
        // 支付方式
        $payment_array = PaymentService::$payment_array;
        $payment = $payment_array[$order_info['payment_id']];
        if(empty($payment))
        {
        	echo json_encode(['code' => -1, 'msg' => '支付方式有误']);
			exit();
        }
        
        //支付参数
        $pay_data = [
        	'user' => $params['user'],
        	'order_id' => $order_info['id'],
        	'order_no' => $order_info['order_no'],
        	'name' => '订单支付',
        	'total_price' => $order_info['price'],
        	'client_type' => 'h5',
        	'notify_url' => request()->domain().'/api/v1/ordernotify/'.strtolower($payment['uppayment']),
        	'call_back_url' => request()->domain().'/h5/pages/order/order',
        	'redirect_url' => '',
        	'site_name' => '摩小妹',
        	'ajax_url' => '',
        ];
        
        
        
        // 发起支付
        $pay_name = 'payment\\'.$payment['uppayment'];
        if($order_info['payment_id']==1){
            $pay_name = 'payment\Weixin';
        }
        $ret = (new $pay_name($payment['config']['user']))->Pay($pay_data);
        if(isset($ret['code']) && $ret['code'] == 0)
        {
        	$result = $ret;
        }else
        {
        	$result['code'] = -100;
        	$result['msg'] = empty($ret['msg']) ? '支付接口异常' : $ret['msg'];
        }
        echo json_encode($result);
	}

	/**
	 * 获取订单列表
	 */
	public function lists()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
//        $params['user']['id'] = 6879;

		
		//dump($params);
		//表单验证
		$validate = $this->validate(
			$params,
			[
				'status' => 'require',
				'page' => 'require'
			],
			[
				'status.require' => '状态有误',
				'page.require' => '分页有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        $map = [
			'user_id' => $params['user']['id'],
			'order_model' => 0,
			'user_is_delete_time' => 0
		];
		if($params['status'] > 0)
		{
			switch ($params['status']) {
				//待支付
				case 1:
				    $map['status'] = 0;
				break;
				//待服务
				case 2:
					$map['status'] = ['in', '1,2,3,4'];
				break;
				//服务中
				case 3:
					$map['status'] = 5;
				break;
				//已完成
				case 4:
					$map['status'] = 6;
				case 5:
					$map['status'] = 9;
				break;
			}
		}
		$list_data = Db::name('order')->where($map)->order('id desc')->limit(($params['page']-1)*10,10)->select();
		if(!empty($list_data))
		{
			//订单状态
			$status_array = OrderService::$status_array;
			//遍历处理
			foreach($list_data as $key => $value)
			{
				//订单状态
				$list_data[$key]['status_name'] = !empty($status_array[$value['status']]['name']) ? $status_array[$value['status']]['name'] : '';
				//查询订单详情
				$order_detail = Db::name('order_detail')->where(['order_id' => $value['id'],'showtype'=>1])->select();
				if(!empty($order_detail))
				{
					foreach($order_detail as $k => $v)
					{
						$order_detail[$k]['images'] = request()->domain().$v['images'];
					}
				}
				$list_data[$key]['order_detail'] = $order_detail;
				//查询服务技师
				$techn_info = Db::name('techn')->field('nickname')->where(['id' => $value['techn_id']])->find();
				$list_data[$key]['techn_info'] = $techn_info;
				//预约时间
				$list_data[$key]['pre_start_time_time'] = !empty($value['add_time']) ? date('Y-m-d H:i:s', $value['add_time']) : '';
				
				$list_data[$key]['jz_type']=2;
                $list_data[$key]['bd_type']=2;
                $list_data[$key]['up_type']=2;
                $list_data[$key]['contact_type']=2;
				
                // if($params['user']['id']==1264||$params['user']['id']==1551||$params['user']['id']==976||$params['user']['id']==5){
    				if($value['status']==5){
    				    $list_data[$key]['jz_type']=1;
                        $list_data[$key]['up_type']=1;
    				}else
    				if($value['status']==6&&time()-$value['pre_end_time']<600){
    				    $list_data[$key]['jz_type']=1;
    				}
    				
                    if($value['status']==9){
                        $list_data[$key]['bd_type']=1;
                    }
                    
                // }
                if($value['status']>=2&&$value['status']<=5){
                    $list_data[$key]['contact_type']=1;
                }elseif($value['status']==6&&time()-$value['pre_end_time']<600){
                    $list_data[$key]['contact_type']=1;
                }
                
                
			}
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		echo json_encode($result);
	}

	/**
	 * 订单取消
	 */
	public function cancel()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'user_id' => $params['user']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if($order_info['status'] != 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //开启事务
        Db::startTrans();
        $upd_data = [
            'status'        => 7,
            'cancel_time'   => time(),
            'upd_time'      => time(),
        ];
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	//事务回滚
        	Db::rollback();
        	echo json_encode(['code' => -1, 'msg' => '取消失败']);
            exit();
        }
        // 订单状态日志添加
        $status_array = OrderService::$status_array;
        $order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $upd_data['status'],
			'msg' => '取消['.$status_array[$order_info['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'user',
			'identity_id' => $order_info['user_id'],
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '取消失败']);
            exit();
		}
		TechnService::TechnPreTimey($order_info['techn_id']);
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '取消成功']);
	}

	/**
	 * 删除订单
	 */
	public function delete()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id'], 'user_id' => $params['user']['id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
//        if(!in_array($order_info['status'], [6,7,8]))
//        {
//        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
//            exit();
//        }
		TechnService::TechnPreTimey($order_info['techn_id']);
        $upd_data = [
            'user_is_delete_time' => time(),
            'upd_time'            => time(),
        ];
        if(Db::name('order')->where(['id' => $order_info['id']])->update($upd_data))
        {
        	$result['code'] = 0;
	        $result['msg'] = "删除成功";
        }else
        {
        	$result['code'] = -1;
	        $result['msg'] = "删除失败";
        }
        echo json_encode($result);
	}
    
    // ************************************************************************************************************
    // 退款页面
    public function refund_index(){
        
        $result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        // 状态
        if(!in_array($order_info['status'], [1,2,3,4]))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        // 订单支付方式校验
        $pay_log = Db::name('pay_log')->where(['order_id' => $order_info['id'], 'business_type' => 1])->find();
        if(empty($pay_log))
        {
        	echo json_encode(['code' => -100, 'msg' => '支付日志不存在']);
			exit();
        }
        //根据不同状态处理不同退款
        $refund_price = $order_info['pay_price'];
        $refund_text='技师未出发前可全额退';
        //退款状态
        $pay_status = 2;
        if($order_info['status'] == 3)
        {
        	//如果技师出发只退服务费用
        	//$refund_price = $order_info['price'];
        	$refund_price = $order_info['pay_price']-$order_info['travel_price'];
        	$pay_status = 3;
            $refund_text='技师已出发，扣除车费';
        }else if($order_info['status'] == 4)
        {
        	//如果技师到达只退一半服务费用
        	$refund_price = PriceNumberFormat(($order_info['pay_price']-$order_info['travel_price'])/2);
        	$pay_status = 3;
            $refund_text='技师已到达，扣除车费+50%的服务费';
        }
        
        $data['price']=$refund_price;
        
        $data['reason']=db::name('reason')->where(['is_delete_time'=>'0'])->select();
        
        $data['refund_text']=$refund_text;
        $result['code'] = 0;
        $result['msg'] = "请求成功";
        $result['data'] = $data;
        echo json_encode($result);
    }
    
    
    // ************************************************************************************************************
    
    
    
    
    
	/**
	 * 用户订单申请退款(先直接根据规则走退款)
	 */
	public function apply_refund()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        // 状态
        if(!in_array($order_info['status'], [1,2,3,4]))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        // 订单支付方式校验
        $pay_log = Db::name('pay_log')->where(['order_id' => $order_info['id'], 'business_type' => 1])->find();
        if(empty($pay_log))
        {
        	echo json_encode(['code' => -100, 'msg' => '支付日志不存在']);
			exit();
        }
        //根据不同状态处理不同退款
        $refund_price = $order_info['pay_price'];
        //退款状态
        $pay_status = 2;
        if($order_info['status'] == 3)
        {
        	//如果技师出发只退服务费用
        	//$refund_price = $order_info['price'];
        	$refund_price = $order_info['pay_price']-$order_info['travel_price'];
        	$pay_status = 3;
        }else if($order_info['status'] == 4)
        {
        	//如果技师到达只退一半服务费用
        	$refund_price = PriceNumberFormat(($order_info['pay_price']-$order_info['travel_price'])/2);
        	$pay_status = 3;
        }
        //判断是否为余额支付
        $is_money = false;
        if($pay_log['payment'] == 'MoneyPay')
        {
        	//是
        	$is_money = true;
        }else
        {
        	//否，原路退回
        	// 操作退款
        	$payment_array = PaymentService::$payment_array;
        	$payment = $payment_array[$order_info['payment_id']];
        	$pay_name = 'payment\\'.$payment['payment'];
        	$pay_params = [
        		'order_id'          => $order_info['id'],
        		'order_no'          => $order_info['order_no'],
        		'trade_no'          => $pay_log['trade_no'],
        		'pay_price'         => $order_info['pay_price'],
        		'refund_price'      => $refund_price,
        		'client_type'       => $order_info['client_type'],
        		'refund_reason'     => $order_info['order_no'].'订单退款'.$refund_price.'元',
        		'pay_time'          => $order_info['pay_time'],
        	];
        	$refund = (new $pay_name($payment['config']['user']))->Refund($pay_params);
        }
        // 退款成功
        if(isset($refund['code']) && $refund['code'] != 0)
        {
            echo json_encode($refund);
			exit();
        }
        // 开启事务
        Db::startTrans();
        //退款日志数据
        $refund_log_data = [];
        // 余额退款
        if($is_money === true)
        {
        	// 获取用户余额
        	$user_info = Db::name('user')->where(['id' => $order_info['user_id']])->find();
        	if(empty($user_info))
        	{
        		Db::rollback();
        		echo json_encode(['code' => -100, 'msg' => '用户不存在']);
			    exit();
        	}
        	// 更新余额数据
        	$money_data = [
	            'money' => Db::raw('money+'.$refund_price),
	            'upd_time' => time()
	        ];
	        if(!Db::name('user')->where(['id' => $user_info['id']])->update($money_data))
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额操作失败']);
			    exit();
	        }
	        //余额日志
	        $money_log_id = Db::name('money_log')->insertGetId([
	            'identity_type' => 'user',
	            'identity_id' => $user_info['id'],
	            'business_type' => 2,
	            'money_type' => 0,
	            'operation_type' => 1,
	            'operation_money' => $refund_price,
	            'original_money' => $user_info['money'],
	            'latest_money' => $user_info['money']+$refund_price,
	            'msg' => '订单退款',
	            'add_time' => time()
	        ]);
	        if($money_log_id <= 0)
	        {
	            Db::rollback();
	            echo json_encode(['code' => -100, 'msg' => '余额日志添加失败']);
			    exit();
	        }
	        $refund_log_data = [
	        	'order_id' => $order_info['id'],
	        	'trade_no' => '',
	        	'buyer_user' => '',
	        	'refund_price' => $refund_price,
	        	'pay_price' => $order_info['pay_price'],
	        	'msg' => '订单退款',
	        	'payment' => $pay_log['payment'],
	        	'payment_name' => $pay_log['payment_name'],
	        	'refundment' => 0,
	        	'business_type' => 1,
	        	'return_params' => '',
	        	'add_time' => time(),
        		'uid'=>$order_info['user_id'],
			    'reason'=>empty($params['reason'])?'':$params['reason'],
			    'day'=>date('Y-m-d')
	        ];
        }else
        {
        	$refund_log_data = [
        		'order_id' => $order_info['id'],
        		'trade_no' => isset($refund['data']['trade_no']) ? $refund['data']['trade_no'] : '',
        		'buyer_user' => isset($refund['data']['buyer_user']) ? $refund['data']['buyer_user'] : '',
        		'refund_price' => isset($refund['data']['refund_price']) ? $refund['data']['refund_price'] : '',
        		'pay_price' => $order_info['pay_price'],
        		'msg' => '订单退款',
        		'payment' => $pay_log['payment'],
        		'payment_name' => $pay_log['payment_name'],
        		'refundment' => 0,
        		'business_type' => 1,
        		'return_params' => isset($refund['data']['return_params']) ? json_encode($refund['data']['return_params'], JSON_UNESCAPED_UNICODE) : '',
        		'add_time' => time(),
        		'uid'=>$order_info['user_id'],
			    'reason'=>empty($params['reason'])?'':$params['reason'],
			    'day'=>date('Y-m-d')
        	];
        }
        //写入退款日志
        $refund_log_id = Db::name('refund_log')->insertGetId($refund_log_data);
        if($refund_log_id <= 0)
        {
        	Db::rollback();
        	echo json_encode(['code' => -100, 'msg' => '退款日志添加失败']);
			exit();
        }
        // 更新主订单
        $order_upd_data = [
        	'pay_status' => $pay_status,
        	'refund_price' => $refund_log_data['refund_price'],
        	'status' => 12, //用户退款
        	'close_time' => time(),
        	'upd_time' => time(),
        ];
        //更新订单状态
        if(!Db::name('order')->where(['id' => $order_info['id']])->update($order_upd_data))
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单更新失败']);
			exit();
		}
		TechnService::TechnPreTimey($order_info['techn_id']);
		//添加状态日志
		$status_array = OrderService::$status_array;

		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $order_info['id'],
			'original_status' => $order_info['status'],
			'new_status' => $order_upd_data['status'],
			'msg' => '退款['.$status_array[$order_info['status']]['name'].'-'.$status_array[$order_upd_data['status']]['name'].']',
			'identity_type' => 'user',
			'identity_id' => $order_info['user_id'],
			'add_time' => time(),
			'reason'=>empty($params['reason'])?'':$params['reason']
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			echo json_encode(['code' => -100, 'msg' => '订单历史状态添加失败']);
			exit();
		}
		//根据状态处理结算日志
		if($order_info['status'] == 3 || $order_info['status'] == 4)
		{
			//处理结算信息
			$balance_list = Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->select();
			if(empty($balance_list))
			{
				Db::rollback();
				echo json_encode(['code' => -1, 'msg' => '结算数据不存在']);
	            exit();
			}
			$balance_ph_count = 0;
			foreach($balance_list as $key => $value)
			{
				switch($value['identity_type'])
				{
					//技师
					case 'techn':
					    if($order_info['status'] == 3)
					    {
					    	//如果技师出发只退服务费用
					    	if($value['balance_type'] != 1)
					    	{
							    //获取技师余额
						        $techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
						        if(empty($techn_info))
								{
									continue;
								}
								// 更新余额数据
								$techn_money_data = [
									'money' => Db::raw('money+'.$value['no_money']),
						            'upd_time' => time()
								];
								if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
								{
									continue;
								}
								//技师余额日志
								$techn_money_log_id = Db::name('money_log')->insertGetId([
						            'identity_type' => 'techn',
						            'identity_id' => $techn_info['id'],
						            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
						            'money_type' => 0,
						            'operation_type' => 1,
						            'operation_money' => $value['no_money'],
						            'original_money' => $techn_info['money'],
						            'latest_money' => $techn_info['money']+$value['no_money'],
						            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
						            'add_time' => time()
						        ]);
						        if($techn_money_log_id <= 0)
						        {
						        	continue;
						        }
						        //更新当前结算信息状态
						        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
								{
									continue;
								}
							}else
							{
								//更新当前结算信息状态
						        if(!Db::name('balance')->where(['id' => $value['id']])->update(['status' => 2, 'upd_time' => time()]))
								{
									continue;
								}
							}
						}else
						{
							//如果技师到达只退一半服务费用
							if($value['balance_type'] == 1)
							{
								$value['no_money'] = PriceNumberFormat($value['no_money']/2);
							}
							$techn_info = Db::name('techn')->where(['id' => $value['identity_id']])->find();
					        if(empty($techn_info))
							{
								continue;
							}
							// 更新余额数据
							$techn_money_data = [
								'money' => Db::raw('money+'.$value['no_money']),
					            'upd_time' => time()
							];
							if(!Db::name('techn')->where(['id' => $techn_info['id']])->update($techn_money_data))
							{
								continue;
							}
							//技师余额日志
							$techn_money_log_id = Db::name('money_log')->insertGetId([
					            'identity_type' => 'techn',
					            'identity_id' => $techn_info['id'],
					            'business_type' => $value['balance_type'] == 2 ? 4 : 5,
					            'money_type' => 0,
					            'operation_type' => 1,
					            'operation_money' => $value['no_money'],
					            'original_money' => $techn_info['money'],
					            'latest_money' => $techn_info['money']+$value['no_money'],
					            'msg' => '技师'.($value['balance_type'] == 2 ? '出行' : '服务').'费用',
					            'add_time' => time()
					        ]);
					        if($techn_money_log_id <= 0)
					        {
					        	continue;
					        }
					        //更新当前结算信息状态
					        if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
							{
								continue;
							}
						}
					break;
					//机构
					case 'proxy':
					    if($order_info['status'] == 3)
					    {
					    	//如果技师出发只退服务费用
					    	//更新当前结算信息状态
					        if(!Db::name('balance')->where(['id' => $value['id']])->update(['status' => 2, 'upd_time' => time()]))
							{
								continue;
							}
					    }else
					    {
					    	//如果技师到达只退一半服务费用
					    	$value['no_money'] = PriceNumberFormat($value['no_money']/2);
					    	//获取机构余额
					    	$proxy_info = Db::name('proxy')->where(['proxy_id' => $value['identity_id']])->find();
					    	if(empty($proxy_info))
							{
								continue;
							}
							// 更新余额数据
							$proxy_money_data = [
								'money' => Db::raw('money+'.$value['no_money']),
						        'upd_time' => time()
							];
							if(!Db::name('proxy')->where(['proxy_id' => $proxy_info['proxy_id']])->update($proxy_money_data))
							{
								continue;
							}
							//机构余额日志
							$proxy_money_log_id = Db::name('money_log')->insertGetId([
						        'identity_type' => 'proxy',
						        'identity_id' => $proxy_info['proxy_id'],
						        'business_type' => 5,
						        'money_type' => 0,
						        'operation_type' => 1,
						        'operation_money' => $value['no_money'],
						        'original_money' => $proxy_info['money'],
						        'latest_money' => $proxy_info['money']+$value['no_money'],
						        'msg' => '机构服务分成费用',
						        'add_time' => time()
						    ]);
						    if($proxy_money_log_id <= 0)
						    {
						    	continue;
						    }
						    //更新当前结算信息状态
						    if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => $value['no_money'], 'status' => 1, 'upd_time' => time()]))
							{
								continue;
							}
					    }
					break;
					//系统
					case 'system':
					    if($order_info['status'] == 3)
					    {
					    	//如果技师出发只退服务费用
					    	//更新当前结算信息状态
					        if(!Db::name('balance')->where(['id' => $value['id']])->update(['status' => 2, 'upd_time' => time()]))
							{
								continue;
							}
					    }else
					    {
					    	//如果技师到达只退一半服务费用
					    	if(!Db::name('balance')->where(['id' => $value['id']])->update(['yes_money' => PriceNumberFormat($value['no_money']/2), 'status' => 1, 'upd_time' => time()]))
							{
								continue;
							}
					    }
					break;
				}
				$balance_ph_count++;
			}
			if($balance_ph_count != count($balance_list))
			{
				Db::rollback();
				echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
				exit();
			}
		}else
		{
			//技师未出发结算状态关闭
			$balance_data = [
				'status' => 2,
				'upd_time' => time()
			];
			if(!Db::name('balance')->where(['order_id' => $order_info['id'], 'status' => 0])->update($balance_data))
			{
				Db::rollback();
				echo json_encode(['code' => -100, 'msg' => '结算记录更新失败']);
				exit();
			}
		}
		//提交事务
		Db::commit();
		echo json_encode(['code' => 0, 'msg' => '退款成功']);
		//发送模板消息
		//查询技师信息
		$techn_info = Db::name('techn')->where(['id' => $order_info['techn_id']])->find();
		if(!empty($techn_info))
		{
			//查询技师关联用户公众号的openid
			$techn_openid = Db::name('user_weixin')->where(['user_id' => $techn_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
			//给技师推送模板消息
			if(!empty($techn_openid))
			{
				//查询订单详情
				$order_detail_title = Db::name('order_detail')->where(['order_id' => $order_info['id']])->column('title');
				// $order_detail_title = implode(',', $order_detail_title);
				$order_detail_title_new='服务项目:'.implode(',',$order_detail_title);
		      //  foreach ($order_detail_title as $k=>$v){
		      //      $order_detail_title_new.="\n ".($k+1).'.'.$v;
		      //  }
				//查询下单人
				$order_address = Db::name('order_address')->where(['order_id' => $order_info['id']])->find();
				$tem_msg['touser'] = $techn_openid;
				$tem_msg['template_id'] = '3q6SrfVd23ZlHepCR2u6xsfEa55OaX8z8bEJsnQ1PL4';
				$tem_msg['miniprogram'] = [
		        	'appid' => TechnWeixinService::$mini_appid,
		        	'pagepath' => 'pages/order/orderdetail?order_id='.$order_info['id']
		        ];
		        $tem_msg['data'] = [
		        	'first' => [
		                'value' => '客户'.$order_address['name'].'已取消订单',
		                'color' => '#173177'
		            ],
		            'keyword1' => [
		                'value' => $order_detail_title_new,
		                'color' => '#173177'
		            ],
		            'keyword2' => [
		                'value' => $order_info['order_no'],
		                'color' => '#173177'
		            ],
		            'keyword3' => [
		                'value' => $refund_log_data['refund_price'].'元',
		                'color' => '#173177'
		            ],
		            'keyword4' => [
		                'value' => '原路返回',
		                'color' => '#173177'
		            ],
		            'remark' => [
		                'value' => '点击查看详情。',
		                'color' => '#173177'
		            ]
		        ];
		        UserWeixinService::send_wx_web_tem_msg($tem_msg);
			}

            //发送退款通知
            $order_info = Db::name('order')->where('id',$order_info['id'])->find();
//            $proxy = Db::name('proxy')->where('shi',$order_info['shi'])->find();
            $proxy_info = Db::name('proxy')->where('qu',$order_info['qu'])->where('is_xian',1)->find();
            if (empty($proxy_info)){
                $proxy_info = Db::name('proxy')->where('shi',$order_info['shi'])->find();
            }
            $proxy = $proxy_info;
            $order_detail_title = Db::name('order_detail')->where(['order_id' => $order_info['id']])->find();

            $send = Db::name('email_list')->where('proxy_id','in',[$proxy['proxy_id'],999])->where('status',1)->column('open_id');
            foreach ($send as $value){
                if (!empty($value)){
                    SendMuLogic::send_mu_refund($value,$order_info,$order_detail_title,$proxy);
                }
            }



			//给用户推送模板消息
			//查询用户的openid
			$user_openid = Db::name('user_weixin')->where(['user_id' => $order_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
			if(!empty($user_openid))
			{
				$tem_msg = [];
				$tem_msg['touser'] = $user_openid;
				$tem_msg['template_id'] = 'zZ7W-JsnM7OwbWnnuPxodYSCpBrGLOY1X0hKDwFHpT4';
				$tem_msg['url'] = request()->domain().'/h5/pages/order/orderdetail?order_id='.$order_info['id'];
				$tem_msg['data'] = [
					'first' => [
		                'value' => '退款通知',
		                'color' => '#173177'
		            ],
		            'keyword1' => [
		                'value' => $order_info['order_no'],
		                'color' => '#173177'
		            ],
		            'keyword2' => [
		                'value' => $techn_info['nickname'],
		                'color' => '#173177'
		            ],
		            'keyword3' => [
		                'value' => '取消预约',
		                'color' => '#173177'
		            ],
		            'keyword4' => [
		                'value' => $order_info['total_price'].'元',
		                'color' => '#173177'
		            ],
		            'remark' => [
		                'value' => '退款'.$refund_log_data['refund_price'].'元，感谢您的使用！',
		                'color' => '#173177'
		            ]
				];
				UserWeixinService::send_wx_web_tem_msg($tem_msg);
			}
		}
	}

	/**
	 * 获取订单详情
	 */
	public function detail()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        //订单状态
        $status_array = OrderService::$status_array;
        $order_info['status_name'] = !empty($status_array[$order_info['status']]['name']) ? $status_array[$order_info['status']]['name'] : '';
        //查询订单状态历史记录
        $order_info['status_history'] = Db::name('order_status_history')->where(['order_id' => $order_info['id']])->column('new_status,identity_type');
        //查询订单详情服务项目
        $order_detail = Db::name('order_detail')->where(['order_id' => $order_info['id'],'showtype'=>1])->select();
        if(!empty($order_detail))
		{
			foreach($order_detail as $k => $v)
			{
			    $msgs='';
			    if($v['type']==1){
			        $msgs='(加钟)';
			    }
				$order_detail[$k]['title'] = $v['title'].$msgs;
				$order_detail[$k]['images'] = request()->domain().$v['images'];
			}
		}
		$order_info['order_detail'] = $order_detail;
		//查询服务技师
		$order_info['techn_info'] = Db::name('techn')->field('nickname')->where(['id' => $order_info['techn_id']])->find();
		//查询订单地址
		$order_info['order_address'] = Db::name('order_address')->where(['order_id' => $order_info['id']])->find();
        //下单时间
        $order_info['add_time_time'] = !empty($order_info['add_time']) ? date('Y-m-d H:i:s', $order_info['add_time']) : '';
        //预约服务时间
        $order_info['pre_start_time_time'] = empty($order_info['local_pre_start_time']) ? date('Y-m-d H:i:s', $order_info['pre_start_time']) : date('Y-m-d H:i:s', $order_info['local_pre_start_time']);
        //预约服务结束时间
        $order_info['pre_end_time_time'] = empty($order_info['local_pre_end_time']) ? date('Y-m-d H:i:s', $order_info['pre_end_time']) : date('Y-m-d H:i:s', $order_info['local_pre_end_time']);
        //支付方式
        $payment_array = PaymentService::$payment_array;
        $order_info['payment_name'] = !empty($payment_array[$order_info['payment_id']]['name']) ? $payment_array[$order_info['payment_id']]['name'] : '';
        //处理订单扩展数据
        $order_info['extension_data'] = !empty($order_info['extension_data']) ? json_decode($order_info['extension_data'], true) : [];
        
        $order_info['jz_type']=2;
        
        if($params['user']['id']==1264){
            if($order_info['status']==5){
    		    $order_info['jz_type']=1;
    		}else
    		if($order_info['status']==6&&time()-$order_info['pre_end_time']<600){
    		    $order_info['jz_type']=1;
    		}
        }
        
        
        $order_info['contact_type']=2;
        if($order_info['status']>=2&&$order_info['status']<=5){
            $order_info['contact_type']=1;
        }elseif($order_info['status']==6&&time()-$order_info['pre_end_time']<600){
            $order_info['contact_type']=1;
        }
                
        $result['code'] = 0;
        $result['msg'] = "请求成功";
        $result['data'] = $order_info;
        echo json_encode($result);   
	}

	/**
	 * 客户联系技师
	 */
	public function contact_techn()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;
		//dump($params);
//        $params['order_id'] = 5103;


		$validate = $this->validate(
			$params,
			[
				'order_id' => 'require'
			],
			[
				'order_id.require' => '订单id有误'
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //查询订单信息
        $order_info = Db::name('order')->where(['id' => $params['order_id']])->find();
        if(empty($order_info))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不存在']);
            exit();
        }
        if(!($order_info['status'] >= 2 && $order_info['status'] <= 5))
        {
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        if($order_info['status']==6&&time()-$order_info['pre_end_time']>600){
        	echo json_encode(['code' => -1, 'msg' => '订单不可操作']);
            exit();
        }
        //技师与下单人绑定隐私电话
        //查询下单人的电话
        $order_address_info = Db::name('order_address')->where(['order_id' => $order_info['id']])->find();
        //查询服务技师
        $techn_info = Db::name('techn')->where(['id' => $order_info['techn_id']])->find();
        //从缓存中读取技师与客户绑定的隐私号码信息
        $yinsi_phone = cache('yinsi_phone_'.$techn_info['mobile']);
        if(!empty($yinsi_phone))
        {
        	//解绑关系
        	$args = [
//        		'poolKey' => 'FC100000167170034',
        		'poolKey' => 'FC100000168856007',
        		'subsId' => $yinsi_phone['subsId'],
        		'secretNo' => $yinsi_phone['secretNo']
        	];
        	\yinsi\Privacy::UnbindSubscription($args);
        }
        //绑定关系
        $args = [
//        	"poolKey" => "FC100000167170034",
        	"poolKey" => "FC100000168856007",
        	"phoneNoA" => $techn_info['mobile'],
        	"phoneNoB" => $params['user']['mobile'],
        	"expiration" => date('Y-m-d H:i:s', time()+(5*60)),
        	"isRecordingEnabled" => true
        ];
        $yinsi_res = \yinsi\Privacy::bindAxb($args);
        if($yinsi_res['code'] != 1)
        {
        	/*echo json_encode(['code' => -1, 'msg' => '请稍后联系']);
            exit();*/
            $yinsi_res['secretNo'] = $techn_info['mobile'];
        }else
        {
        	//绑定关系存入缓存
        	cache('yinsi_phone_'.$techn_info['mobile'], $yinsi_res);
        }
        $result['code'] = 0;
		$result['msg'] = '请求成功';
		$result['data'] = $yinsi_res;
		echo json_encode($result);
	}
	
	
	
	
}